#
# @lc app=leetcode.cn id=110 lang=python3
#
# [110] 平衡二叉树
#
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
# @lc code=start
# Definition for a binary tree node.

class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        return self.depth(root) != -1

    def depth(self, root: TreeNode) -> int:
        if root is None:
            return 0
        leftDepth = self.depth(root.left)
        # 提前终止，剪枝
        if leftDepth == -1:
            return -1
        
        rightDepth = self.depth(root.right)
        if rightDepth == -1 or abs(leftDepth - rightDepth) > 1:
            return -1
        return max(leftDepth, rightDepth) + 1
# @lc code=end

